package com.luoqiz.project.mulThreadCopy;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class MulCopyThread extends Thread{

	private int byteSize = 1024;// 每次写入字节数组长度
	private String srcFile;		//源文件
	private String destPath;	//目标路径
	private long startPoint;	//起始帧
	private long endPoint;		//截止帧
	
	public int getByteSize() {
		return byteSize;
	}
	public void setByteSize(int byteSize) {
		this.byteSize = byteSize;
	}
	public MulCopyThread() {}
	public MulCopyThread(String srcPath,String destPath,long start,long end) {
		this.srcFile=srcPath;
		this.destPath=destPath;
		this.startPoint=start;
		this.endPoint=end;
	}
	@Override
	public void run() {
		RandomAccessFile srdaf = null;
		RandomAccessFile drdaf = null;
		try {
			srdaf = new RandomAccessFile(srcFile, "r");
			drdaf = new RandomAccessFile(new File(destPath), "rw");
			srdaf.seek(startPoint);
			drdaf.seek(startPoint);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		long threadCopyLen=endPoint-startPoint;
//		long start = (i - 1) * threadCopyLen;
//		long end = start + threadCopyLen;
//		if (i == threadNum) {
//			end += a;
//		}
		System.out.println(Thread.currentThread().getName() + "===开始--" + startPoint + "--结束" + endPoint);
		byte[] b = new byte[byteSize];
		int loopNum = (int) (threadCopyLen / byteSize);
		// System.out.println(loopNum);
		if (threadCopyLen % byteSize != 0) {
			loopNum++;
		}
		try {
			for (int forNum = 0; forNum < loopNum; forNum++) {
				if (forNum == (loopNum - 1)) {
					int last = (int) (threadCopyLen - forNum * byteSize);
					srdaf.read(b, 0, last);
					drdaf.write(b, 0, last);
					// System.out.println("线程号：" + i + "**last:" + forNum + "-" + last);
				} else {
					srdaf.read(b, 0, byteSize);
					drdaf.write(b, 0, byteSize);
					// System.out.println("线程号：" + i + "**ttt:" + forNum + "-" );
				}
			}
			try {
				srdaf.close();
				drdaf.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName()  + "拷贝完成");
	}
}
